const fs = require("fs");
const cheerio = require("cheerio");
const superagent = require("superagent");
const moment = require("moment");
const path = require("path");

const huilvURL = "https://quote.fx678.com/exchange/WH";

let num3 = 0;

function getExchangeJson() {
  superagent.get(huilvURL, (err, res) => {
    if (err) console.error(err);
    const $ = cheerio.load(res.text);
    let $tr1 = $("#WH tbody").children().eq(9);
    let $tr2 = $("#WH tbody").children().eq(10);
    let USDCNY = Number($tr1.children().eq(1).html());
    let USDCNH = Number($tr2.children().eq(1).html());
    let id = Date.now();
    if (USDCNH != 0 && USDCNY != 0) {
      let newsList = {
        id: id,
        USDCNY: USDCNY,
        USDCNH: USDCNH,
      };
      writeJson(newsList);
    }

    //写入模块
    function writeJson(params) {
      let serverTime = moment(Date.now()).format("YYYY-MM-DD");
      let fileName =
        "../jsonserver/DataBase/exchange/exchangeLCNY" + serverTime + ".json";
      //现将json文件读出来
      fs.readFile(path.join(fileName), function (err, data2) {
        if (err) {
          let data = [];
          let length = 0;
          let firList = {
            data,
            length,
          };
          var firData = JSON.stringify(firList);
          fs.writeFile(path.join(fileName), firData, function (err) {
            if (err) {
              console.error(err);
            }
          });
          console.log("创建" + fileName + "成功！");
        }
        var p1 = data2.toString(); //将二进制的数据转换为字符串
        var p = JSON.parse(p1); //将字符串转换为json对象
        p.data.push(params); //将传来的对象push进数组对象中
        p.total = p.data.length; //定义一下总条数，为以后的分页打基础
        var str = JSON.stringify(p); //因为nodejs的写入文件只认识字符串或者二进制数，所以把json对象转换成字符串重新写入json文件中
        fs.writeFile(path.join(fileName), str, function (err) {
          if (err) {
            S;
            console.error(err);
          }
          num3++;
          let current_time = moment(Date.now()).format("YYYY-MM-DD HH:mm:ss");
          console.log("Exchange爬取次数：" + num3 + " |time：" + current_time);
        });
      });
    }
  });
}
//汇率爬虫模块-end

//定时爬取
function toGet() {
  getExchangeJson();
  setInterval(getExchangeJson, 180000);
}

module.exports.exchange = toGet;
